<?php
/**
 * trace 运行追踪类
 * @authors moufer (moufer@163.com)
 * @date    2015-01-04 13:35:53
 * @version $Id$
 */

class ms_trace {

	protected static $logs = array();
	
	/**
	 * 记录运行日志
	 * @param  string $logstr  记录内容
	 * @param  string $cate 记录类型，留空为 common
	 * @param  string $act  记录行为，留空为 common
	 * @return void
	 */
	public static function log($logstr, $cate = '', $act = '')
	{
		if(!$cate) $cate = 'common';
		if(!$act) $act = 'common';
		static::$logs[$cate][$act][] = $logstr;
	}

	/**
	 * 在浏览器中显示当前页面的运行记录
	 * @param  boolean $echo 是否直接输出在缓冲中
	 * @return string        如果不输出在缓冲中，则返回成字符串格式
	 */
	public static function print_log($echo = true)
	{
		if($_GET) foreach ($_GET as $key => $value) {
			static::log("$key = "._T($value), 'input', 'GET');
		}
		if($_POST) foreach ($_POST as $key => $value) {
			static::log("$key = ".($value?_T($value):''), 'input', 'POST');
		}
		if($_COOKIE) foreach ($_COOKIE as $key => $value) {
			static::log("$key = ".($value?_T($value):''), 'input', 'COOKIE');
		}
		//session数据
		foreach (_G('session')->fetch_all() as $key => $value) {
			static::log("$key = ".($value?_T($value):''), 'input','Session');
		}
		//全部已加载的文件
		$included_files = get_included_files();
		foreach ($included_files as $value) {
			static::log($value, 'file', 'included_files');
		}
		//DB缓存
		$dbcache = _G('dbcache')->fetch_data_all();
		foreach ($dbcache as $value) {
			static::log(var_export($value, true), 'cache', 'dbcache');
		}

		if(!static::$logs) return;
		$content = '';
		$style = 'margin:5px auto;width:98%;line-height:18px;font-family:Courier New;text-align:left;background:#eee;border-width:1px; border-style:solid;border-color:#CCC;';
		foreach (static::$logs as $key => $value) {
			 foreach($value as $k => $v) {
				$content .='<div style="'.$style.'">';
				$id = 'debug_log_' . $key . '_' . $k;
				$content .='<h3 style="font-size:16px;border-bottom:1px solid #FF9900;margin:5px;padding:0 0 5px;">
					<a href="javascript:;" onclick="$(\'#'.$id.'\').toggle();">'.$key.' '.$k.'</a> ('.count($v).')</h3>';
				$content .= '<ul style="margin:0;padding:0 0 5px;list-style:none;display:none;" id="'.$id.'">';
				foreach ($v as $_v) {
					$content .= '<li style="padding:1px 8px;font-size:12px;">' . str_replace(MUDDER_ROOT, '', $_v) . '</li>';
				}
				$content .= '</ul>';
				$content .= '</div>';
			}
		}

		if($echo) {
			echo $content;
		} else {
			return $content;
		}
	}

	/**
	 * backtrace信息转换为文本格式
	 * @param  array $trace_array backtrace信息
	 * @return string
	 */
	public static function backtrace_to_txt($trace_array)
	{
	    $t = '';
	    foreach ($trace_array as $trace) {
	        $t .= str_replace(MUDDER_ROOT, DS, str_replace(array("\\","/"), DS, $trace['file']))
	            ."\t".$trace['line']
	            ."\t".($trace['class']?("{$trace['class']}::"):'')
	            .$trace['function']."()\n";
	    }
	    $t .= request_uri()."\n";
	    return $t;
	}

}

/** end */